#!/usr/bin/env node

const path = require('path')
const fs = require('fs')
const TmxToLevelConverter = require('./TmxToLevelConverter')
const prettier = require('prettier')

const levelsFolder = path.resolve(__dirname, '../levels')
const outputLevelsFilePath = path.resolve(__dirname, '../src/levels.js')

const levelNames = fs
  .readdirSync(levelsFolder)
  .filter(name => name.endsWith('.tmx'))
  .map(name => path.basename(name, '.tmx'))
  .sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))

console.log(`Compiling ${levelNames.length} levels from ${levelsFolder} to ${outputLevelsFilePath}`)

const levels = []
const tmxToLevelConverter = new TmxToLevelConverter()
for (let levelIndex = 0; levelIndex < levelNames.length; ++levelIndex) {
  const levelName = levelNames[levelIndex]
  console.log('>', levelIndex, levelName)
  const xml = fs.readFileSync(path.resolve(levelsFolder, `${levelName}.tmx`), 'utf8')
  const level = tmxToLevelConverter.tmxToLevel(xml, levelIndex)
  levels.push(level)
}
levels[levels.length - 1].last = 1

const output = `// autogenerated file
const levels = ${JSON.stringify(levels)}
`

const prettierConfig = prettier.resolveConfig.sync(__dirname)
const outputFormatted = prettier.format(output, { ...prettierConfig, filepath: outputLevelsFilePath })
fs.writeFileSync(outputLevelsFilePath, outputFormatted)

console.log('ok.')
